package com.example.fourm.controller;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import com.example.fourm.config.AppConfig;
import com.example.fourm.exception.ApplicationException;
import com.example.fourm.model.Message;
import com.example.fourm.model.User;
import com.example.fourm.services.IMessageService;
import com.example.fourm.services.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IUserService userService;
    @Resource
    private IMessageService messageService;
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @RequestParam("content") @NonNull String content) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getState() == 1) {
            log.warn("用户为空或者用户不能发私信");
            throw new ApplicationException(AppResult.failure("发送私信失败"));
        }
        if(user.getId() == receiveUserId){
            return AppResult.failure("不能自己给自己发私信");
        }
        Long postId = user.getId();
        User reUser = userService.selectByPrimaryKey(receiveUserId);
        if (reUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        messageService.create(message);
        return AppResult.success();
    }

    //获取未读数
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Integer count = messageService.selectUnreadCount(user.getId());
        return AppResult.success(count);

    }

    @GetMapping("getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messages);
    }

    @PostMapping("/markRead")
    public AppResult markRead(@RequestParam("id") @NonNull Long id ,HttpServletRequest request) {
        Message message = messageService.selectById(id);
        if(message == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString()+"站内信不存在");
            return AppResult.failure(ResultCode.FAILED_NOT_EXISTS.toString());
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getId() != message.getReceiveUserId()){
           return AppResult.failure(ResultCode.FAILED);
        }
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    //回复站内信
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @RequestParam("repliedId") @NonNull Long repliedId,
                           @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User postUser = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(postUser.getState() == 1){
            return AppResult.failure(ResultCode.FAILED_USER_BANNED);
        }
        Message existMessage = messageService.selectById(repliedId);
        if(existMessage == null){
            log.warn("站内信不存在");
            return AppResult.failure(ResultCode.FAILED_NOT_EXISTS.toString());
        }
        if(postUser.getId() == existMessage.getPostUserId()){
            return AppResult.failure("不能回复自己的站内信");
        }
        Message newMessage = new Message();
        newMessage.setPostUserId(postUser.getId());
        newMessage.setContent(content);
        newMessage.setReceiveUserId(existMessage.getPostUserId());
        messageService.reply(repliedId, newMessage);
        return AppResult.success();
    }
}
